import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { useUserInfoStore } from '@/mobx';

function Auth() {
  const { userInfo } = useUserInfoStore();
  const { pathname } = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (!userInfo?.token && pathname !== '/login') {
      navigate('/login', { replace: true });
    } else if (userInfo?.token && pathname === '/login') {
      navigate(-1);
    }
  }, [userInfo?.token, pathname, navigate]);

  return null;
}

export default observer(Auth);
